#!/usr/bin/env python3
import os
import sys
import re
from datetime import datetime

def fix_hardcoded_indicators():
    print("=== 修复HTML响应中的硬编码指标数据 ===")
    print(f"时间: {datetime.now()}\n")
    
    # 1. 检查app.py文件
    print("1. 检查app.py文件...")
    app_path = "app.py"
    
    if not os.path.exists(app_path):
        print(f"错误: 找不到{app_path}文件")
        return
    
    with open(app_path, 'r', encoding='utf-8') as f:
        app_content = f.read()
    
    # 2. 检查是否有缓存控制代码
    print("2. 检查是否有缓存控制代码...")
    
    cache_control_code = '''
@app.after_request
def add_header(response):
    # Add HTTP headers to disable browser cache
    response.headers["Cache-Control"] = "no-store, no-cache, must-revalidate, post-check=0, pre-check=0, max-age=0"
    response.headers["Pragma"] = "no-cache"
    response.headers["Expires"] = "-1"
    return response
'''
    
    if "@app.after_request" in app_content and "Cache-Control" in app_content:
        print("✅ 已存在缓存控制代码")
    else:
        print("❌ 未找到缓存控制代码, 将添加...")
        
        # 在app.run前添加缓存控制代码
        if "if __name__ == '__main__'" in app_content:
            app_content = app_content.replace(
                "if __name__ == '__main__'", 
                cache_control_code + "\nif __name__ == '__main__'"
            )
            
            with open(app_path, 'w', encoding='utf-8') as f:
                f.write(app_content)
            print("✅ 已添加缓存控制代码")
        else:
            print("❌ 无法找到合适的位置添加缓存控制代码")
    
    # 3. 检查index.html模板
    print("\n3. 检查index.html模板...")
    template_path = "templates/index.html"
    
    if not os.path.exists(template_path):
        print(f"错误: 找不到{template_path}文件")
        return
    
    with open(template_path, 'r', encoding='utf-8') as f:
        template_content = f.read()
    
    # 4. 检查是否有硬编码的已移除指标
    print("4. 检查是否有硬编码的已移除指标...")
    
    removed_indicators = {
        'stochastic k': '22.88',
        'williams %r': '-77.12', 
        'cci': '-48.71',
        'momentum': '98.31'
    }
    
    found_indicators = False
    for indicator, value in removed_indicators.items():
        if indicator in template_content.lower() or value in template_content:
            found_indicators = True
            print(f"❌ 发现指标: {indicator} = {value}")
    
    if not found_indicators:
        print("✅ 模板中未发现硬编码的已移除指标")
    
    # 5. 检查是否有动态注入的JavaScript代码
    print("\n5. 检查是否有动态注入的JavaScript代码...")
    
    js_pattern = r'<script[^>]*>([\s\S]*?)</script>'
    scripts = re.findall(js_pattern, template_content)
    
    found_js_indicators = False
    for script in scripts:
        for indicator, value in removed_indicators.items():
            if indicator in script.lower() or value in script:
                found_js_indicators = True
                print(f"❌ JavaScript中发现指标: {indicator} = {value}")
    
    if not found_js_indicators:
        print("✅ JavaScript中未发现硬编码的已移除指标")
    
    # 6. 创建修复方案
    print("\n6. 创建修复方案...")
    
    print("\n修复方案:")
    print("1. 已添加HTTP头禁用浏览器缓存")
    print("2. 请清除浏览器缓存 (使用clear_browser_cache.py获取详细步骤)")
    print("3. 重启Flask应用")
    print("4. 使用私密/隐身模式访问应用")
    
    # 7. 提供验证步骤
    print("\n7. 验证步骤:")
    print("1. 重启Flask应用")
    print("2. 清除浏览器缓存")
    print("3. 访问应用并检查HTML源代码")
    print("4. 确认已移除指标不再显示")

if __name__ == "__main__":
    fix_hardcoded_indicators()